package com.blackhorse.anlis.anli_tx.factory;

import com.blackhorse.service.AccountService;
import com.blackhorse.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 用于创建Serviec代理对象的工厂
 */
public class ServiceBeanFactory {
    private AccountService accountService;
    private TransactionManager transactionManager;

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * 获得到AccountService的代理对象
     *
     * @return
     */
    public AccountService getAccountService() {
        AccountService proxy_accountService = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object rtValue = null;
                        //添加事务的支持
                        System.out.println("代理对象添加对方法增强");
                        try {
                            //1.开启事务
                            transactionManager.beginTransaction();
                            //2.执行操作
                            rtValue = method.invoke(accountService, args);
                            //3.提交事务
                            System.out.println("事务提交");
                            transactionManager.commit();
                            //4.返回结果
                            return rtValue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("发生异常，事务回滚");
                            //5.事务回滚
                            transactionManager.rollback();
                            return null;
                        } finally {
                            //6.释放连接
                            transactionManager.release();
                        }
                    }
                });
        return proxy_accountService;
    }
}
